package com.c.service.impl;

import com.c.pojo.entity.Account;
import com.c.pojo.entity.Answer;
import com.c.pojo.vo.AnswerVo;
import com.c.repository.AccountRepository;
import com.c.service.AccountService;
import com.c.service.AnswerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @author bysun
 */
@Service
public class AccountServiceImpl implements AccountService {

    @Resource
    AccountRepository accountRepository;

    @Resource
    AnswerService answerService;

    @Override
    public Account addAccount(Account account) {
        account.setUpdateTime(new Date());
        account = accountRepository.save(account);
        return account;
    }

    @Override
    public List<Account> getAccounts() {
        return accountRepository.findAccountsByIsDeleteFalse();
    }

    @Override
    public Account getAccount(Integer id) {
        return accountRepository.getOne(id);
    }

    @Override
    public Account updateAccount(Account account) {
        account.setUpdateTime(new Date());
        return accountRepository.save(account);
    }

    @Override
    public void delAccount(Integer id) {
        if (id != null) {
            Answer answer = answerService.getAnswerByAccountId(id);
            if (answer != null) {
                AnswerVo answerVo = new AnswerVo();
                answerVo.setId(answer.getId());
                answerVo.setAccountId(id);
                answerVo.setDelete(true);
                answerVo.setDescription(answer.getDescription());
                answerVo.setPicUrl(answer.getPicUrl());
                answerVo.setTitle(answer.getTitle());
                answerVo.setUrl(answer.getUrl());
                answerService.addOrUpdateAnswer(answerVo);
            }
            Account account = accountRepository.getOne(id);
            account.setDelete(true);
            account.setUpdateTime(new Date());
            accountRepository.save(account);
        }
    }

}
